import EventManager from '../event.js';

class BaseSprite {
    constructor(app, name) {
        this.app = app;
        this.name = name;
        this.sprites = [];
        this.loaded = false;
        this.active = true;
    }

    // 子类需要实现的方法
    async loadResources() {
        throw new Error('loadResources method must be implemented');
    }

    async init() {
        throw new Error('init method must be implemented');
    }

    update(deltaTime) {
        // 可选实现，用于帧更新
    }

    destroy() {
        this.sprites.forEach(sprite => {
            if (sprite.parent) {
                sprite.parent.removeChild(sprite);
            }
            sprite.destroy();
        });
        this.sprites = [];
        this.active = false;
    }

    // 通用方法
    addSprite(sprite) {
        this.sprites.push(sprite);
        this.app.stage.addChild(sprite);
    }

    removeSprite(sprite) {
        const index = this.sprites.indexOf(sprite);
        if (index > -1) {
            this.sprites.splice(index, 1);
            if (sprite.parent) {
                sprite.parent.removeChild(sprite);
            }
        }
    }

    // 事件注册辅助方法
    registerEvents() {
        // 子类可以重写来注册特定事件
    }

    unregisterEvents() {
        // 子类可以重写来取消事件注册
    }

    // 生命周期管理
    async setup() {
        await this.loadResources();
        await this.init();
        this.registerEvents();
        this.loaded = true;
    }

    cleanup() {
        this.unregisterEvents();
        this.destroy();
    }

    isLoaded() {
        return this.loaded;
    }

    isActive() {
        return this.active;
    }

    setActive(active) {
        this.active = active;
        this.sprites.forEach(sprite => {
            sprite.visible = active;
        });
    }
}

export default BaseSprite;
